package com.example.network_services_twit_begin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Base64;

public class AuthorisationManager {
	
	private static final String CONSUMER_KEY = "lHjptjaAE4IRQkPXiWQMQw";
	private static final String CONSUMER_SECRET = "AQLobvH6TNerMh0DSAmC1YfiYU5vBzS8txKYZ38hLRc";
	private static String bearerToken;
	
	public static void signWithBearerToken(HttpRequestBase httpRequest)
	{
		if (bearerToken == null){
			getBearerToken();			
		} 
		
		httpRequest.setHeader("Authorization", "Bearer " + bearerToken);
	}
	
	private static void getBearerToken()
	{
		HttpClient client = new DefaultHttpClient();	
		HttpPost request = new HttpPost("https://api.twitter.com/oauth2/token");	
		ResponseHandler<String> handler = new BasicResponseHandler();
		
		String authString = CONSUMER_KEY + ":" + CONSUMER_SECRET;
		String authStringBase64 = Base64.encodeToString(authString.getBytes(), 
		Base64.NO_WRAP);
		request.setHeader("Authorization", "Basic " + authStringBase64);
		request.setHeader("Content-Type", 
		"application/x-www-form-urlencoded;charset=UTF-8");
		try {
			request.setEntity(new StringEntity("grant_type=client_credentials"));
			
			String response = client.execute(request, handler);

			JSONObject obj = new JSONObject(response);
			bearerToken = obj.getString("access_token");
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
}
